<?php

namespace app\admin\controller\user;

use app\admin\model\BillModel;
use app\admin\model\Building as BuildingModel;
use app\admin\model\BuildingRoomModel;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 用户合同
 *
 * @icon fa fa-circle-o
 */
class Contract extends Backend
{

    /**
     * Contract模型对象
     * @var \app\admin\model\user\Contract
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Contract;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("yaTypeList", $this->model->getYaTypeList());
        $this->view->assign("moonChaoStatusList", $this->model->getMoonChaoStatusList());
        $this->view->assign("userTypeList", $this->model->getUserTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $build_ids = BuildingModel::getUserBuildingIds($this->auth->id);

            $where = [];
            $where['build_id'] = ['in', $build_ids];

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function audit()
    {
        $id = $this->request->param('ids/d', 0);
        if ($id < 1) {
            $this->error('参数错误');
        }

        $contract = $this->model->get($id);

        if (empty($contract)) {
            $this->error('合同不存在');
        }
        Db::startTrans();
        try {
            // =========  生成账单 =========
            //首次租金
            $rent_date = date('Y-m-' . $contract['rent_day']);
            $period = date('Y-m-d') . '至' . date('Y-m-d', strtotime('next month -1 day', strtotime($rent_date)));
            if ($contract['first_zu'] > 0) {
                BillModel::create([
                    'user_id' => $contract['homeowner_id'],
                    'contract_id' => $id,
                    'status' => 0,
                    'money' => $contract['first_zu'],
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => '租金',
                    'type' => 1,
                    'remark' => '租金',
                    'period' => $period,
                ]);
            }

            // 房租押金
            if ($contract['money_ya'] > 0) {
                BillModel::create([
                    'user_id' => $contract['homeowner_id'],
                    'contract_id' => $id,
                    'status' => 2,
                    'money' => $contract['money_ya'],
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => '押金',
                    'type' => 2,
                    'remark' => '房租押金',
                    'expire_date' => $contract['end_time'],
                ]);
            }
            // 配套押金
            if (!empty($params['pt'])) {
                $pt_money = array_sum(array_column($params['pt'], 'deposit'));
                if ($pt_money > 0) {
                    BillModel::create([
                        'user_id' => $contract['homeowner_id'],
                        'contract_id' => $id,
                        'status' => 2,
                        'money' => $pt_money,
                        'year' => date('Y'),
                        'month' => date('Y-m'),
                        'day' => date('Y-m-d'),
                        'category' => '押金',
                        'type' => 2,
                        'remark' => '配套设备押金',
                        'expire_date' => $params['end_time'],
                    ]);
                }
            }

            $contract->status = 1;
            $contract->save();
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    public function revoke_audit()
    {
        $id = $this->request->param('ids/d', 0);

        if ($id < 1) {
            $this->error('参数错误');
        }
        $contract = $this->model->get($id);
        if (empty($contract)) {
            $this->error('合同不存在');
        }
        Db::startTrans();
        try {
            BillModel::destroy([
                'contract_id' => $id,
                'status' => ['in', [0, 1]],
            ]);
            $contract->status = 0;
            $contract->save();

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    public function del($ids =  null)
    {
        $ids = $this->request->param('ids');

        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $item->data('del_uid', $this->auth->id);
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error('删除失败');
    }

}
